Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Variables

Multi assignments

Assigning Multiple Values to Multiple Variables

Python allows you to assign multiple values to multiple variables in one line. This is done by separating the variable names and the values with commas.
Assigning multiple values to multiple variables example in python x, y, z = 1, 2, 3 print(x) print(y) print(z)

Output

1 2 3
In this example, 1 is assigned to x, 2 is assigned to y, and 3 is assigned to z.

Assigning the Same Value to Multiple Variables

You can also assign the same value to multiple variables in one line:
Assigning the same value to multiple variables example in python x = y = z = 1 print(x) print(y) print(z)

Output

1 1 1
In this example, 1 is assigned to x, y, and z.

Unpacking a Collection

If you have a collection of values in a list or tuple, Python allows you to extract the values into variables. This is called unpacking.
Assigning values by unpacking list or tuple example in python fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z)

Output

apple banana cherry
In this example, ""apple"" is assigned to x, ""banana"" is assigned to y, and ""cherry"" is assigned to z. Please note that when assigning multiple values to multiple variables, the number of variables must match the number of values, or else you will get an error.

  📌TAGS

★python ★ variable ★ global variable

Tutorials